package ru.nosport.matrixaria.core;


import org.w3c.dom.Document;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.util.logging.XMLFormatter;
import java.util.logging.Handler;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


/**
 * User: vfabr
 * Date: 25.12.2006
 * Time: 19:14:46
 */
public class MatrixariaXMLFormater extends XMLFormatter {

	public MatrixariaXMLFormater() {
		super();
	}

	public String getHead(Handler h) {return "";}

	public String getTail(Handler h) {return "";}

	static public Document strToDoc(String _xmlStr){
		Document ret = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			ret = docBuilder.parse(new ByteArrayInputStream(_xmlStr.getBytes()));
		} catch (ParserConfigurationException ignore) {
			ignore.printStackTrace();
		} catch (IOException ignore) {
			ignore.printStackTrace();
		} catch (SAXException ignore) {
			ignore.printStackTrace();
		}

		return ret;
	}

	static public String docToStr(Document _xmlDoc){
		DOMImplementationLS domImplementation = (DOMImplementationLS) _xmlDoc.getImplementation();
		LSSerializer lsSerializer = domImplementation.createLSSerializer();

		return lsSerializer.writeToString(_xmlDoc);
	}

}